<template>
    <el-drawer v-model="isShow" direction="rtl" :destroy-on-close="true" :size="550">
        <template #header>
            <h2 class="title">{{ title }}</h2>
        </template>

        <template #default>
            <schema-form ref="schemaFormRef" :schema="components[name]?.schema" v-loading="loading" />
        </template>

        <template #footer>
            <el-button type="primary" @click="save">
                {{ saveBtnText }}
            </el-button>
        </template>
    </el-drawer>
</template>

<script setup>
import { ref, inject } from 'vue'
import SchemaForm from '$widget/schema-form/schema-form.vue'
import $curl from '$common/curl.js'
import { ElNotification } from 'element-plus'

const emit = defineEmits(['command'])
const schemaFormRef = ref(null)
const name = ref('createForm')
const isShow = ref(false)
const title = ref('')
const saveBtnText = ref('保存')
const loading = ref(false)
const { components, api } = inject('schemaViewData')

const show = () => {
    const { config } = components.value[name.value];
    title.value = config.title;
    saveBtnText.value = config.saveBtnText;
    isShow.value = true;
}

const close = () => {
    isShow.value = false;
}
const save = async () => {
    if (!loading.value) {
        return;
    }
    if (!schemaFormRef.value.validate()) { return; }

    loading.value = true;
    const res = await $curl({
        method: 'post',
        url: api.value,
        data: {
            ...schemaFormRef.value.getValue()
        }
    });
    loading.value = false;

    if (!res || !res.success) {
        return;
    }

    ElNotification({
        title: '创建成功',
        message: '创建成功',
        type: 'success'
    });
    close();

    emit('command', 'loadTableData');
}

defineExpose({
    name,
    show,
})
</script>

<style scoped lang="less">
.create-form {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
}
</style>
